<template>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="add-admin-form"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="分类" prop="task_category_id">
        <el-select
          v-model="form.task_category_id"
          placeholder="请选择分类"
          clearable
        >
          <el-option label="请选择分类" :value="null" disabled />
          <el-option v-for="item in taskCategoryList" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="金额" prop="price">
        <el-input v-model="form.price" placeholder="请输入金额" type="number" />
      </el-form-item>
      
      <el-form-item label="封面图" prop="cover">
        <el-upload
          :action="action"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="coverRemove"
          name="file"
          :headers="{ 'Authorization':  token }"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          accept=".jpg,.jpeg,.png,.gif"
          :show-file-list="false"
          :on-exceed="handleExceed"
        >
          <div v-if="form.cover">
            <img :src="form.cover" alt="封面图" style="max-height: 146px;max-width: 146px;" />
          </div>
          <div v-else>
            <el-icon><Plus /></el-icon>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="附件上传" prop="attachment">
        <el-upload
          :action="action"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          name="file"
          :headers="{ 'Authorization':  token }"
          :on-success="handleSuccessFile"
          :on-exceed="handleExceedFile"
          :show-file-list="false"
          accept=".pdf,.doc,.docx,.xls,.xlsx,.txt"
        >
        <template #trigger>
          <el-button size="small" type="text">请选择附件</el-button>
        </template>
          <div v-if="form.attachment">
            <span>{{ form.attachment }}</span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <Editor
          v-if="editorVisible"
          :formData="form"
          @content="content"
          label="内容"
          prop="content"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" placeholder="请输入排序" type="number" />
      </el-form-item>
      <el-form-item label="创建时间" prop="created_at"  v-if="isEdit">
        <el-input v-model="form.created_at" placeholder="创建时间" disabled/>
      </el-form-item>
      <el-form-item label="更新时间" prop="updated_at" v-if="isEdit">
        <el-input v-model="form.updated_at" placeholder="更新时间" disabled/>
      </el-form-item>
      <el-form-item label="上传附件" prop="is_attachment">
        <el-radio-group v-model="form.is_attachment">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </template>
  
  <script setup>
  import { ref, reactive, watch, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import  Editor from '@/components/Editor.vue'
  const upload = ref();
  const token = ref(localStorage.getItem('token'));
  //访问 api/index.js 的baseURL
  const action = ref("/adminApi/upload");

  // 定义组件接收的属性
  const props = defineProps({
    formData: {
      type: Object, // 表单数据对象
      default: () => null // 默认值为 null
    },
    isEdit: {
      type: Boolean, // 是否为编辑模式
      default: false // 默认值为 false
    },
    taskCategoryList: {
      type: Object, // 任务分类列表
      default: () => {} // 默认值为空数组
    }
  });
  console.log('Initial formData:', props.formData); // 打印初始传入的 formData
  // 表单元素的引用
  const formRef = ref(null);

  // 响应式表单数据对象
  const form = reactive({
    title: props.formData?.title || '', // 从 props 获取标题，默认为空字符串
    cover: props.formData?.cover || '', // 从 props 获取封面图 URL，默认为空字符串
    status: 1, // 默认状态为启用
    attachment: props.formData?.attachment || '', // 从 props 获取附件 URL，默认为空字符串
    content: props.formData?.content || '', // 从 props 获取内容，默认为空字符串
    task_category_id: props.formData?.task_category_id || null, // 从 props 获取任务分类 ID，默认为 "请选择分类"
    price: props.formData?.price || 0, // 从 props 获取金额，默认为 0
    sort: props.formData?.sort || 0 ,// 从 props 获取排序值，默认为 0
    is_attachment:props.formData?.is_attachment || 0
  });
  
  // 监听 formData 变化
  watch(() => props.formData, (newVal, oldVal) => {
    console.log('AddTaskForm - formData updated:', newVal, 'oldVal:', oldVal); // 打印新旧值
    if (newVal && Object.keys(newVal).length > 0) {
      Object.assign(form, newVal); // 更新表单数据
      console.log('AddTaskForm - Updated form:', form); // 打印更新后的表单数据
    } else {
      console.warn('AddTaskForm - formData is null or empty, resetting form to default values.');
      resetForm(); // 调用重置表单方法
    }
  }, { immediate: true });
  
  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    Object.assign(form, {
      title: '',
      cover:'',
      status: '',
      attachment:'',
      task_category_id: 0,
      price: 0,
      content: '',
      sort: 0,
      is_attachment:0
    });
  };
  
  // 验证规则
  const rules = {
    title: [
      { required: true, message: '请输入标题', trigger: 'blur' },
      { min: 2, max: 20, message: '标题长度在2到20个字符之间', trigger: 'blur' }
    ],
    price: [
      { required: true, message: '请输入金额', trigger: 'blur' },
    
      //不能为负数
      { validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('金额不能为负'));
        } else {
          callback();
        }
        }, trigger: 'blur' }
    ],
    task_category_id: [
      { required: true, message: '请选择分类', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' }
    ]
  };
  
  const validateForm = async () => {
    try {
      await formRef.value.validate();
      return true;
    } catch (error) {
      ElMessage.error('请检查表单填写是否正确');
      return false;
    }
  };
  
   const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/'); // 检查 MIME 类型是否以 "image/" 开头
    if (!isImage) {
      ElMessage.error('只能上传图片!');
      return false;
    }
  
    const isLt2M = file.size / 1024 / 1024 < 2000; // 限制图片大小为 2MB
    if (!isLt2M) {
      ElMessage.error('上传图片大小不能超过 2000MB!');
      return false;
    }
  
    return true;
  };
  
  const handleSuccess = (response) => {
    if (response.code === 1) {
      form.cover = response.data; // 假设返回的数据中有文件的URL
      ElMessage.success('上传成功');
    } else {
      ElMessage.error('上传失败');
    }
  };
  
  const coverRemove = (file, fileList) => {
    form.cover = '';
  };
  
  const handleSuccessFile = (response) => {
    if (response.code === 1) {
      form.attachment = response.data; // 假设返回的数据中有文件的URL
      ElMessage.success('上传成功');
    } else {
      ElMessage.error('上传失败');
    }
  };
  
  const handleExceedFile = (files) => {
  if (upload.value) {
    upload.value.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    if (upload.value.handleStart) {
      upload.value.handleStart(file);
    }
  }
};

  const handleExceed = (files) => {
    // ElMessage.warning('文件数量超出限制，仅允许上传一个文件');
    // if (upload.value) {
    //   upload.value.clearFiles();
    // }
  }

  const handlePictureCardPreview = (file, fileList) => {
    
  };

  const handleRemove = (file, fileList) => {
    
  };

  // 内容发生变化时触发
  const content = (e) => {
  console.log('Content changed:', e); // 打印内容变化
  form.content = /<\/?[a-z][\s\S]*>/i.test(e) ? e : '<p></p>'; // 确保内容为 HTML 格式
  }

  const editorVisible = ref(false); // 控制编辑器的显示状态

  onMounted(() => {
    // 页面加载完成后显示编辑器
    editorVisible.value = true;
  });

  defineExpose({
    formRef,
    form,
    validateForm,
    resetForm
  });
  </script>
  
  <style scoped>
  
  .el-upload-list--picture-card {
    height: 60px;
    width: 60px;
  }
  .ql-toolbar.ql-snow {
    width: 100% !important;
    box-sizing: border-box; /* 确保宽度计算正确 */
  }
  </style>